package com.pphh.demo;

import java.util.LinkedList;
import java.util.List;

/**
 * memory leak demo with infinite strings creation
 * <p>
 * test command :
 * java -Xms8m -Xmx8m -Xmn8m -classpath "./target/classes" com.pphh.demo.DemoStringCreation
 *
 * @author huangyinhuang
 * @date 8/22/2018
 */
public class DemoStringCreation {

    public static List<String> stringHeap = new LinkedList<>();

    /**
     * exception message on java version "1.8.0_111"
     * <p>
     * Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
     * at java.util.Arrays.copyOfRange(Arrays.java:3664)
     * at java.lang.String.<init>(String.java:207)
     * at java.lang.StringBuilder.toString(StringBuilder.java:407)
     * at java.util.Formatter.toString(Formatter.java:2355)
     * at java.lang.String.format(String.java:2940)
     * at com.pphh.demo.DemoStringCreation.main(DemoStringCreation.java:25)
     *
     * @param args arguments
     */
    public static void main(String[] args) {

        Long i = 0L;
        String s = "";
        try {
            for (; i < 1000 * 1000; ) {
                s = String.format("test-%s", s);
                stringHeap.add(s);
                Thread.sleep(10);
                System.out.println(i++);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
